﻿/*******************************************************
Copyright © 2007-2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommunityServer.Controls;
using System.Web.UI;
using CommunityServer.Components;
using System.ComponentModel;
using System.IO;

namespace ATGi.CS.BrightCove.Controls
{
    public class BrightCoveVideoQuery : QueryOverrideBase, IAttributeAccessor
    {
        //No reason to apply to different object. All uses can use control instance.
        public override void ApplyQueryOverrides(object query) { }

        /// <summary>
        /// Gets or sets the sort order.
        /// </summary>
        /// <value>The sort order.</value>
        public BCSortOrder SortOrder
        {
            get
            {
                object var = ViewState["SortOrder"];
                return var == null ? BCSortOrder.ASC : (BCSortOrder)var;
            }
            set { ViewState["SortOrder"] = value; }
        }

        public BCSortByType SortBy
        {
            get
            {
                object var = ViewState["SortBy"];
                return var == null ? BCSortByType.PUBLISH_DATE : (BCSortByType)var;
            }
            set { ViewState["SortBy"] = value; }
        }

        public List<string> Fields
        {
            get { return (List<string>)ViewState["Fields"]; }
            set { ViewState["Fields"] = value; }
        }

        /// <summary>
        /// Gets or sets the search text applied for a text type search.
        /// </summary>
        /// <value>The search text.</value>
        public string SearchText
        {
            get { return ((string)ViewState["SearchText"]) ?? string.Empty; }
            set { ViewState["SearchText"] = value; }
        }

        string[] _referenceIds;
        /// <summary>
        /// Gets or sets the comma-separated list of reference ids to retrieve.
        /// </summary>
        /// <value>The reference ids.</value>
        public string ReferenceIds
        {
            get { return ((string)ViewState["ReferenceIds"]) ?? string.Empty; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    ViewState["ReferenceIds"] = "";
                    _referenceIds = new string[0];
                }
                else
                {
                    ViewState["ReferenceIds"] = value;
                    _referenceIds = value.Split(',');
                }
            }
        }

        public string UserID
        {
            get { return (string)ViewState["UserID"]; }
            set { ViewState["UserID"] = value; }
        }

        public long CampaignID
        {
            get { return (long)ViewState["CampaignID"]; }
            set { ViewState["CampaignID"] = value; }
        }

        public long VideoID
        {
            get { return (long)ViewState["VideoID"]; }
            set { ViewState["VideoID"] = value; }
        }

        ITemplate _videoIdTemplate;

        [
           Browsable(false),
           DefaultValue(null),
           PersistenceMode(PersistenceMode.InnerProperty),
        ]
        public ITemplate VideoIDTemplate
        {
            get { return _videoIdTemplate; }
            set { _videoIdTemplate = value; }
        }
        /// <summary>
        /// Gets or sets the type of this query; the generic location/relationship from which data will be retrieved.
        /// </summary>
        /// <value>The type of the query.</value>
        public BrightCoveVideoQueryType QueryType
        {
            get
            {
                object var = ViewState["QueryType"];
                return var == null ? BrightCoveVideoQueryType.All : (BrightCoveVideoQueryType)var;
            }
            set { ViewState["QueryType"] = value; }
        }

        Control templateWrapper;
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if(_videoIdTemplate != null)
            {
                templateWrapper = new Control();
                this.Controls.Add(templateWrapper);
                _videoIdTemplate.InstantiateIn(templateWrapper);
                GetVideoIdTemplateValue();
            }
        }

        protected virtual void GetVideoIdTemplateValue()
        {
            if (templateWrapper != null)
            {
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                templateWrapper.DataBind();
                templateWrapper.RenderControl(htw);
                htw.Flush();
                string templateValue = sw.ToString().Trim();
                long parsedValue;
                if (!String.IsNullOrEmpty(templateValue) && long.TryParse(templateValue, out parsedValue))
                    this.VideoID = parsedValue;
            }
        }

        #region IAttributeAccessor Members
        public string GetAttribute(string key)
        {
            return this.Attributes[key];
        }

        public void SetAttribute(string key, string value)
        {
            this.Attributes[key] = value;
        }

        private System.Collections.Specialized.NameValueCollection _attributes = null;
        protected System.Collections.Specialized.NameValueCollection Attributes
        {
            get
            {
                if (_attributes == null)
                    _attributes = new System.Collections.Specialized.NameValueCollection();

                return _attributes;
            }
        }
        #endregion
    }

    /// <summary>
    /// Indicates the type of search to perform against the media API
    /// </summary>
    public enum BrightCoveVideoQueryType
    {
        /// <summary>
        /// All videos available based on token.
        /// </summary>
        All,
        /// <summary>
        /// Any video with a matching campaign id.
        /// </summary>
        Campaign,
        /// <summary>
        /// All videos matching the given tags
        /// </summary>
        Tags,
        /// <summary>
        /// Any video matching the given text
        /// </summary>
        Text,
        /// <summary>
        /// All videos related to the given video by id.
        /// </summary>
        Related,
        /// <summary>
        /// All videos with the given BC user id.
        /// </summary>
        User,
    }
}
